var express = require("express");
var router = express.Router();
const multer = require("multer");
const path = require("path");
const fs = require("fs");

const { RbacUserModel, PermissionModel, RoleModel, RolePermissionModel, UserRoleModel, YonghuUserModel, YonghuOrderModel, YonghuCouponModel } = require('../db');
const { generateTokens, verifyRefreshToken } = require('../utils/jwt');
const { sendResetPasswordCode } = require('../utils/emailService');
const authMiddleware = require('../middleware/auth');
const AlipaySdk = require('alipay-sdk').default;
const AlipayFormData = require("alipay-sdk/lib/form").default

// 头像上传配置
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = path.join(__dirname, "../upload/avatars");
    // 确保目录存在
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 生成唯一的文件名
    const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
    const ext = path.extname(file.originalname);
    cb(null, "avatar-" + uniqueSuffix + ext);
  },
});

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 2 * 1024 * 1024, // 2MB
  },
  fileFilter: function (req, file, cb) {
    // 只允许图片格式
    const allowedTypes = /jpeg|jpg|png|gif|webp/;
    const extname = allowedTypes.test(
      path.extname(file.originalname).toLowerCase()
    );
    const mimetype = allowedTypes.test(file.mimetype);

    if (mimetype && extname) {
      return cb(null, true);
    } else {
      cb(new Error("只允许上传图片格式的文件"));
    }
  },
});

// 凭证照片上传配置
const evidenceStorage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = path.join(__dirname, '../upload/evidence');
    // 确保目录存在
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 生成唯一的文件名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname);
    cb(null, 'evidence-' + uniqueSuffix + ext);
  }
});

const evidenceUpload = multer({
  storage: evidenceStorage,
  limits: {
    fileSize: 2 * 1024 * 1024 // 2MB
  },
  fileFilter: function (req, file, cb) {
    // 只允许图片格式
    const allowedTypes = /jpeg|jpg|png|gif|webp/;
    const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
    const mimetype = allowedTypes.test(file.mimetype);
    
    if (mimetype && extname) {
      return cb(null, true);
    } else {
      cb(new Error('只允许上传图片格式的文件'));
    }
  }
});

// 支付宝SDK配置
const alipaySdk = new AlipaySdk({
  appId: '9021000150653655', // 支付宝沙箱应用ID
  privateKey: 'MIIEpQIBAAKCAQEAxmwkL605qOGR3SQV/geOk7y0+CrNXWxiPwWpMLoWtgzo60cfVbGmoLahdnnrKbb07oCPEnJMGu7IRsimpf0cQkNcdsNqNPZLbMTFIWJSDL8yJGrp6I2rUajPlDyTa5v/YgKFKy1nMYM1QCdxvB++C9f3QqLMPaGpwfBFCswcj8R4E+9UDrZiJ2oSpR4a6Zas+CUMBhF8Z2tAgjHzLZfHf3LADsO+lqHRBkAQP4nQo0tWuQr5Jycfx614+Jhjx7AOIsjxL6uvlDXR1eCqrFqH53/6AKKlq52KjXVVxppvUhJqbwS0K5LyVP0jB4iUXJwBhtlpUeG+O3mkiNk5s7d/9QIDAQABAoIBAQDGMTxP1vISCwW8YpAJBhlW3hXREEfC+kCD/K6LekS3INwCLi9RVDpAq0tJ4OuQ5ituk0DVRw9Xk4y+jytN/y0bztbr1bMfJagfA8h32RJloxB9qcDsRZ2K2lhFE+CYiuAjUKsdfqNlpE4rP3ruUrJseBKFH8FsCi9bBRiheVFKE00uZCNU8/aQQb8iN3x80ETEgLkvLC5Ixi+9vn33yZCUIFDVl8LJz2//1xx05YIXHKRZs3kTLM3LbhgRigb+h3lbHt3rSnSRByEGNKjsof7oY/7Di3fMT6qqGOS3Rsd5FxJAmnTmplGQsWn5knUovjh00ZpxDc7vu0d+cYfhjTXdAoGBAONlFnu38o4G/bkJgdnAm13+2QWnu5GPPgeWIvWyvMby7llxblFCnrgqTuzmNIBQ0oe2V/CX1r9JmQqV/RXsvlSxUSybl72D7bKYIourqnd4JAsphdTs6DHC/HAMiuAvC3MiONKrwYH0QjBSGSF/BEw38yTRMcquGU204F2gOkv/AoGBAN9iCgYGDuOZvJS49zwcM87yBGayqUHNsq6Bk4+bYwAGrEtXb1qK7/ZxlN4FA6Vox5yimQ4sT35DkWZ/qbiLpQYWU9gDnT9udwTtsvycUb1CmusjfPWRt7OBSOXZ7WZhN6Q3yAPcx3Q82XT6nUiP/5iLbvFIpki6ym2u8fy8+cQLAoGANBrQuQ6gVK0DbGfiSiwZLcOcpPAXSbZB52ken6ASI6A8v1//gD08s0R2i1AAjbp3U0OUCPwx5+kMWWGe+Wwi/LMYv5jzfyiAyeCUYd63E+MCl1Ava2fRmL1uLJqjI9WD0SDxVkym7YkztXDKc2Nwb6qOW0xYFXIpOCYPF0UEtq8CgYEAhGuXyY5Z0S5Xjko/tZB6Xdk2JrMOhwWrQKtrkBvrCh7qkBca2a+3JH6cYyjRyoJcokv5M1+tGApx7TMMp2uQvhUKSumJlAql33QRQJJiGjGbqHx3HRPutCiV0Dvp8WD8HQs8NJ3yVsOjnSbbiiJiwEkX0Uzh1gd07KRiqxJTdZUCgYEAhYs7t8WJZOB5q/j/FDyYcpXrlXg6Eipf9oMDz96sXrRL5lSCoaCesJlnddsaEchseR/+r1Cnq4fxj/bt2gJThkEAkfCKqGI+bIiiiga8mqsbRi0OgOm5kX5JoAAxdiItruHk8OpWHDv0aN3BuPJ2mWKlarBCClayupS6d9UNGbQ=', // 应用私钥
  gateway: 'https://openapi-sandbox.dl.alipaydev.com/gateway.do', // 沙箱网关
  alipayPublicKey: 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnwyMNzALTH99N6g9/+61b/MC2nCP/WL/XKUXOzmV/xbFisgwXaoV/1jUEiavq+Cr5eNNTTpApq7oKqwijRswB50uxMO1zI7m2Tgpv7XLTcVc1F2cjNLAlqbm0INueI98lNDvwD4QaFcs92LOHRClUOEFqRmk4Fsqk92B7YqlpfZpmvtOXICXzx2o9b0SA+xkFAl/CPunJGSsAOfVauzXCuEIRdcr2clGMEKjdTKwA7HjcBQcFbCDvPZK9w0jZm3lE84cmCNLFpH3AybmJwDPC3Ok7LC0DoxirVNEc62AobvVmZ6jCa5SeFKOnQrzZl5vc2NlUm7ewR4//UPFKwhNgQIDAQAB', // 支付宝公钥
  timeout: 30000, // 关键：延长超时时间30s
  signType: 'RSA2'
});

/* GET home page. */
router.get("/", function (req, res, next) {
  res.render("index", { title: "Express" });
});

// ======rbac权限管理======

// ======用户管理路由======
// 获取用户列表
router.get("/user", async function (req, res, next) {
  try {
    const { page = 1, limit = 10, search = "" } = req.query;
    const skip = (page - 1) * limit;

    let query = {};
    if (search) {
      query = {
        $or: [
          // $options: 'i' 表示不区分大小写
          { userName: { $regex: search, $options: "i" } },
          { realName: { $regex: search, $options: "i" } },
          { email: { $regex: search, $options: "i" } },
        ],
      };
    }

    const users = await RbacUserModel.find(query)
      .skip(skip)
      .limit(parseInt(limit))
      .sort({ _id: 1 });

    const total = await RbacUserModel.countDocuments(query);

    res.json({
      code: 200,
      message: "获取用户列表成功",
      data: {
        list: users,
        total,
        page: parseInt(page),
        limit: parseInt(limit),
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取用户列表失败",
      error: error.message,
    });
  }
});

// 获取用户角色列表
router.get("/user/:id/roles", async function (req, res, next) {
  try {
    const user = await RbacUserModel.findById(req.params.id);
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: "用户不存在",
      });
    }

    // 获取用户角色
    const userRoles = await UserRoleModel.find({ userId: req.params.id });
    const roleIds = userRoles.map((ur) => ur.roleId);
    const roles = await RoleModel.find({ _id: { $in: roleIds } });

    res.json({
      code: 200,
      message: "获取用户角色成功",
      data: {
        user,
        roles,
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取用户角色失败",
      error: error.message,
    });
  }
});

// 新增用户
router.post("/user", async function (req, res, next) {
  try {
    const {
      userName,
      passWord,
      realName,
      email,
      phone,
      roleIds = [],
    } = req.body;

    // 检查用户名是否已存在
    const existingUser = await RbacUserModel.findOne({ userName });
    if (existingUser) {
      return res.status(400).json({
        code: 400,
        message: "用户名已存在",
      });
    }

    // 生成用户ID
    const userId = `user_${Date.now()}`;

    // 创建用户
    const user = new RbacUserModel({
      _id: userId,
      userName,
      passWord,
      realName,
      email,
      phone,
    });

    const savedUser = await user.save();

    // 分配角色
    if (roleIds.length > 0) {
      const userRoles = roleIds.map((roleId) => ({
        userId: savedUser._id,
        roleId,
      }));
      await UserRoleModel.insertMany(userRoles);
    }

    res.json({
      code: 200,
      message: "新增用户成功",
      data: savedUser,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "新增用户失败",
      error: error.message,
    });
  }
});

// 编辑用户
router.put("/user/:id", async function (req, res, next) {
  try {
    const { userName, realName, email, phone, status, roleIds = [] } = req.body;

    // 检查用户是否存在
    const user = await RbacUserModel.findById(req.params.id);
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: "用户不存在",
      });
    }

    // 检查用户名是否被其他用户使用
    if (userName && userName !== user.userName) {
      const existingUser = await RbacUserModel.findOne({
        userName,
        _id: { $ne: req.params.id },
      });
      if (existingUser) {
        return res.status(400).json({
          code: 400,
          message: "用户名已存在",
        });
      }
    }

    // 更新用户信息
    const updateData = {
      userName: userName || user.userName,
      realName: realName || user.realName,
      email: email || user.email,
      phone: phone || user.phone,
      status: status || user.status,
      updatedAt: new Date(),
    };

    const updatedUser = await RbacUserModel.findByIdAndUpdate(
      req.params.id,
      updateData,
      { new: true }
    );

    // 更新用户角色
    if (roleIds !== undefined) {
      // 删除原有角色
      await UserRoleModel.deleteMany({ userId: req.params.id });
      // 添加新角色
      if (roleIds.length > 0) {
        const userRoles = roleIds.map((roleId) => ({
          userId: req.params.id,
          roleId,
        }));
        await UserRoleModel.insertMany(userRoles);
      }
    }

    res.json({
      code: 200,
      message: "编辑用户成功",
      data: updatedUser,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "编辑用户失败",
      error: error.message,
    });
  }
});

// 删除用户
router.delete("/user/:id", async function (req, res, next) {
  try {
    const user = await RbacUserModel.findById(req.params.id);
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: "用户不存在",
      });
    }

    // 删除用户
    await RbacUserModel.findByIdAndDelete(req.params.id);

    // 删除用户角色关联
    await UserRoleModel.deleteMany({ userId: req.params.id });

    res.json({
      code: 200,
      message: "删除用户成功",
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "删除用户失败",
      error: error.message,
    });
  }
});

// ======角色管理路由======
// 获取角色列表
router.get("/role", async function (req, res, next) {
  try {
    const { page = 1, limit = 10, search = "" } = req.query;
    const skip = (page - 1) * limit;

    let query = {};
    if (search) {
      query = {
        $or: [
          { name: { $regex: search, $options: "i" } },
          { code: { $regex: search, $options: "i" } },
        ],
      };
    }

    const roles = await RoleModel.find(query)
      .skip(skip)
      .limit(parseInt(limit))
      .sort({ _id: 1 });

    const total = await RoleModel.countDocuments(query);

    res.json({
      code: 200,
      message: "获取角色列表成功",
      data: {
        list: roles,
        total,
        page: parseInt(page),
        limit: parseInt(limit),
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取角色列表失败",
      error: error.message,
    });
  }
});

// 获取所有角色列表（用于选择）
router.get("/roles/all", async function (req, res, next) {
  try {
    const roles = await RoleModel.find({ status: "active" }).sort({ _id: 1 });

    res.json({
      code: 200,
      message: "获取角色列表成功",
      data: roles,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取角色列表失败",
      error: error.message,
    });
  }
});

// 获取角色权限树（用于权限分配）
router.get("/role/:id/permissions", async function (req, res, next) {
  try {
    const role = await RoleModel.findById(req.params.id);
    if (!role) {
      return res.status(404).json({
        code: 404,
        message: "角色不存在",
      });
    }

    // 获取角色已分配的权限ID列表
    const rolePermissions = await RolePermissionModel.find({
      roleId: req.params.id,
    });
    const assignedPermissionIds = rolePermissions.map((rp) =>
      rp.permissionId.toString()
    );

    // 获取所有权限并构建树形结构
    const permissions = await PermissionModel.find({ status: "active" }).sort({
      sort: 1,
    });

    const buildTree = (items, parentId = null) => {
      return items
        .filter((item) => {
          if (parentId === null) {
            return !item.parentId || item.parentId === "";
          }
          return item.parentId === parentId;
        })
        .map((item) => ({
          ...item.toObject(),
          children: buildTree(items, item._id),
        }));
    };

    const tree = buildTree(permissions);

    res.json({
      code: 200,
      message: "获取角色权限树成功",
      data: {
        role,
        permissionTree: tree,
        assignedPermissionIds,
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取角色权限树失败",
      error: error.message,
    });
  }
});

// 获取角色用户列表
router.get("/role/:id/users", async function (req, res, next) {
  try {
    const role = await RoleModel.findById(req.params.id);
    if (!role) {
      return res.status(404).json({
        code: 404,
        message: "角色不存在",
      });
    }

    // 获取拥有该角色的用户
    const userRoles = await UserRoleModel.find({ roleId: req.params.id });
    const userIds = userRoles.map((ur) => ur.userId);
    const users = await RbacUserModel.find({ _id: { $in: userIds } });

    res.json({
      code: 200,
      message: "获取角色用户列表成功",
      data: {
        role,
        users,
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取角色用户列表失败",
      error: error.message,
    });
  }
});

// 新增角色
router.post("/role", async function (req, res, next) {
  try {
    const { name, code, description, permissionIds = [] } = req.body;

    // 检查角色代码是否已存在
    const existingRole = await RoleModel.findOne({ code });
    if (existingRole) {
      return res.status(400).json({
        code: 400,
        message: "角色代码已存在",
      });
    }

    // 生成角色ID
    const roleId = `role_${Date.now()}`;

    // 创建角色
    const role = new RoleModel({
      _id: roleId,
      name,
      code,
      description,
    });

    const savedRole = await role.save();

    // 分配权限（只分配二级菜单权限）
    if (permissionIds.length > 0) {
      const validPermissionIds = [];
      for (const permissionId of permissionIds) {
        const permission = await PermissionModel.findById(permissionId);
        if (permission && permission.parentId) {
          validPermissionIds.push(permissionId);
        }
      }

      if (validPermissionIds.length > 0) {
        const rolePermissions = validPermissionIds.map((permissionId) => ({
          roleId: savedRole._id,
          permissionId,
        }));
        await RolePermissionModel.insertMany(rolePermissions);
      }
    }

    res.json({
      code: 200,
      message: "新增角色成功",
      data: savedRole,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "新增角色失败",
      error: error.message,
    });
  }
});

// 编辑角色
router.put("/role/:id", async function (req, res, next) {
  try {
    const { name, code, description, status, permissionIds = [] } = req.body;

    // 检查角色是否存在
    const role = await RoleModel.findById(req.params.id);
    if (!role) {
      return res.status(404).json({
        code: 404,
        message: "角色不存在",
      });
    }

    // 检查角色代码是否被其他角色使用
    if (code && code !== role.code) {
      const existingRole = await RoleModel.findOne({
        code,
        _id: { $ne: req.params.id },
      });
      if (existingRole) {
        return res.status(400).json({
          code: 400,
          message: "角色代码已存在",
        });
      }
    }

    // 更新角色信息
    const updateData = {
      name: name || role.name,
      code: code || role.code,
      description: description || role.description,
      status: status || role.status,
      updatedAt: new Date(),
    };

    const updatedRole = await RoleModel.findByIdAndUpdate(
      req.params.id,
      updateData,
      { new: true }
    );

    // 更新角色权限
    if (permissionIds !== undefined) {
      // 过滤掉一级菜单的权限ID，只保留二级菜单
      const validPermissionIds = [];
      for (const permissionId of permissionIds) {
        const permission = await PermissionModel.findById(permissionId);
        if (permission && permission.parentId) {
          validPermissionIds.push(permissionId);
        }
      }

      // 删除原有权限
      await RolePermissionModel.deleteMany({ roleId: req.params.id });

      // 添加新权限
      if (validPermissionIds.length > 0) {
        const rolePermissions = validPermissionIds.map((permissionId) => ({
          roleId: req.params.id,
          permissionId,
        }));
        await RolePermissionModel.insertMany(rolePermissions);
      }
    }

    res.json({
      code: 200,
      message: "编辑角色成功",
      data: updatedRole,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "编辑角色失败",
      error: error.message,
    });
  }
});

// 删除角色
router.delete("/role/:id", async function (req, res, next) {
  try {
    const role = await RoleModel.findById(req.params.id);
    if (!role) {
      return res.status(404).json({
        code: 404,
        message: "角色不存在",
      });
    }

    // 删除角色
    await RoleModel.findByIdAndDelete(req.params.id);

    // 删除角色权限关联
    await RolePermissionModel.deleteMany({ roleId: req.params.id });

    // 删除用户角色关联
    await UserRoleModel.deleteMany({ roleId: req.params.id });

    res.json({
      code: 200,
      message: "删除角色成功",
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "删除角色失败",
      error: error.message,
    });
  }
});

// 分配角色权限
router.post("/role/:id/permissions", async function (req, res, next) {
  try {
    const { permissionIds = [] } = req.body;

    const role = await RoleModel.findById(req.params.id);
    if (!role) {
      return res.status(404).json({
        code: 404,
        message: "角色不存在",
      });
    }

    // 过滤掉一级菜单的权限ID，只保留二级菜单
    const validPermissionIds = [];
    for (const permissionId of permissionIds) {
      const permission = await PermissionModel.findById(permissionId);
      if (permission && permission.parentId) {
        validPermissionIds.push(permissionId);
      }
    }

    // 删除原有权限
    await RolePermissionModel.deleteMany({ roleId: req.params.id });

    // 添加新权限
    if (validPermissionIds.length > 0) {
      const rolePermissions = validPermissionIds.map((permissionId) => ({
        roleId: req.params.id,
        permissionId,
      }));
      await RolePermissionModel.insertMany(rolePermissions);
    }

    res.json({
      code: 200,
      message: "权限分配成功",
      data: {
        roleId: req.params.id,
        permissionIds: validPermissionIds,
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "权限分配失败",
      error: error.message,
    });
  }
});

// ======权限管理路由======
// 获取所有权限列表（用于选择）
router.get("/permissions/all", async function (req, res, next) {
  try {
    // 获取一级和二级所有菜单用于树形选择器
    const permissions = await PermissionModel.find({ status: "active" }).sort({
      sort: 1,
    });
    res.json({
      code: 200,
      message: "获取权限列表成功",
      data: permissions,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取权限列表失败",
      error: error.message,
    });
  }
});

// 获取权限列表
router.get("/permission", async function (req, res, next) {
  try {
    const { page = 1, limit = 10, search = "", parentId } = req.query;
    const skip = (page - 1) * limit;

    let query = {};
    if (search) {
      query = {
        $or: [
          { name: { $regex: search, $options: "i" } },
          { code: { $regex: search, $options: "i" } },
        ],
      };
    }

    if (parentId) {
      query.parentId = parentId;
    }
    // 获取所有二级菜单，先按parentId排序，再按sort排序
    // 确保parentId存在
    // $ne:不等于
    // const permissions = await PermissionModel.find({ status: 'active',parentId:{$ne:null} }).sort({parentId:1,sort:1});
    const permissions = await PermissionModel.find({
      ...query,
      parentId: { $ne: null },
    })
      .skip(skip)
      .limit(parseInt(limit))
      .sort({ parentId: 1, sort: 1 });

    const total = await PermissionModel.countDocuments(query);

    res.json({
      code: 200,
      message: "获取权限列表成功",
      data: {
        list: permissions,
        total,
        page: parseInt(page),
        limit: parseInt(limit),
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取权限列表失败",
      error: error.message,
    });
  }
});

// 获取权限树形结构
router.get("/permission/tree", async function (req, res, next) {
  try {
    const permissions = await PermissionModel.find({ status: "active" }).sort({
      sort: 1,
    });

    // 构建树形结构
    const buildTree = (items, parentId = null) => {
      return items
        .filter((item) => {
          if (parentId === null) {
            return !item.parentId || item.parentId === "";
          }
          return item.parentId === parentId;
        })
        .map((item) => ({
          ...item.toObject(),
          children: buildTree(items, item._id),
          // 移除disabled属性，允许一级菜单可选择
        }));
    };

    const tree = buildTree(permissions);

    res.json({
      code: 200,
      message: "获取权限树成功",
      data: tree,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取权限树失败",
      error: error.message,
    });
  }
});

// 新增权限
router.post("/permission", async function (req, res, next) {
  try {
    const { name, code, description, parentId, path, icon, sort, isShow } =
      req.body;

    // 检查权限代码是否已存在
    const existingPermission = await PermissionModel.findOne({ code });
    if (existingPermission) {
      return res.status(400).json({
        code: 400,
        message: "权限代码已存在",
      });
    }

    // 检查权限路径是否已存在
    if (path) {
      const existingPath = await PermissionModel.findOne({ path });
      if (existingPath) {
        return res.status(400).json({
          code: 400,
          message: "权限路径已存在",
        });
      }
    }

    // 生成权限ID
    let permissionId;
    if (parentId) {
      // 二级菜单：parentId-number
      const childCount = await PermissionModel.countDocuments({ parentId });
      permissionId = `${parentId}-${childCount + 1}`;
    } else {
      // 一级菜单：数字
      const parentCount = await PermissionModel.countDocuments({
        parentId: null,
      });
      permissionId = `${parentCount + 1}`;
    }

    // 创建权限
    const permission = new PermissionModel({
      _id: permissionId,
      name,
      code,
      description,
      parentId,
      path,
      icon,
      sort: sort || 0,
      isShow: isShow || false,
    });

    const savedPermission = await permission.save();

    res.json({
      code: 200,
      message: "新增权限成功",
      data: savedPermission,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "新增权限失败",
      error: error.message,
    });
  }
});

// 编辑权限
router.put("/permission/:id", async function (req, res, next) {
  try {
    const {
      name,
      code,
      description,
      parentId,
      path,
      icon,
      sort,
      isShow,
      status,
    } = req.body;

    // 检查权限是否存在
    const permission = await PermissionModel.findById(req.params.id);
    if (!permission) {
      return res.status(404).json({
        code: 404,
        message: "权限不存在",
      });
    }

    // 检查权限代码是否被其他权限使用
    if (code && code !== permission.code) {
      const existingPermission = await PermissionModel.findOne({
        code,
        _id: { $ne: req.params.id },
      });
      if (existingPermission) {
        return res.status(400).json({
          code: 400,
          message: "权限代码已存在",
        });
      }
    }

    // 检查权限路径是否被其他权限使用
    if (path && path !== permission.path) {
      const existingPath = await PermissionModel.findOne({
        path,
        _id: { $ne: req.params.id },
      });
      if (existingPath) {
        return res.status(400).json({
          code: 400,
          message: "权限路径已存在",
        });
      }
    }

    // 更新权限信息
    const updateData = {
      name: name || permission.name,
      code: code || permission.code,
      description: description || permission.description,
      parentId: parentId || permission.parentId,
      path: path || permission.path,
      icon: icon || permission.icon,
      sort: sort !== undefined ? sort : permission.sort,
      isShow: isShow !== undefined ? isShow : permission.isShow,
      status: status || permission.status,
      updatedAt: new Date(),
    };

    const updatedPermission = await PermissionModel.findByIdAndUpdate(
      req.params.id,
      updateData,
      { new: true }
    );

    res.json({
      code: 200,
      message: "编辑权限成功",
      data: updatedPermission,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "编辑权限失败",
      error: error.message,
    });
  }
});

// 获取权限角色列表
router.get("/permission/:id/roles", async function (req, res, next) {
  try {
    const permission = await PermissionModel.findById(req.params.id);
    if (!permission) {
      return res.status(404).json({
        code: 404,
        message: "权限不存在",
      });
    }

    // 获取拥有该权限的角色
    const rolePermissions = await RolePermissionModel.find({
      permissionId: req.params.id,
    });
    const roleIds = rolePermissions.map((rp) => rp.roleId);
    const roles = await RoleModel.find({ _id: { $in: roleIds } });

    res.json({
      code: 200,
      message: "获取权限角色列表成功",
      data: {
        permission,
        roles,
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取权限角色列表失败",
      error: error.message,
    });
  }
});

// 删除权限
router.delete("/permission/:id", async function (req, res, next) {
  try {
    const permission = await PermissionModel.findById(req.params.id);
    if (!permission) {
      return res.status(404).json({
        code: 404,
        message: "权限不存在",
      });
    }

    // 检查是否有子权限
    const childPermissions = await PermissionModel.find({
      parentId: req.params.id,
    });
    if (childPermissions.length > 0) {
      return res.status(400).json({
        code: 400,
        message: "该权限下有子权限，无法删除",
      });
    }

    // 删除权限
    await PermissionModel.findByIdAndDelete(req.params.id);

    // 删除角色权限关联
    await RolePermissionModel.deleteMany({ permissionId: req.params.id });

    res.json({
      code: 200,
      message: "删除权限成功",
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "删除权限失败",
      error: error.message,
    });
  }
});

// ======用户登录和权限验证======
// 用户登录
router.post("/login", async function (req, res, next) {
  try {
    const { userName, passWord } = req.body;

    // 查找用户
    const user = await RbacUserModel.findOne({ userName, passWord });
    if (!user) {
      return res.status(401).json({
        code: 401,
        message: "用户名或密码错误",
      });
    }

    if (user.status !== "active") {
      return res.status(403).json({
        code: 403,
        message: "用户已被禁用",
      });
    }

    // 获取用户角色和权限
    const userRoles = await UserRoleModel.find({ userId: user._id });
    const roleIds = userRoles.map((ur) => ur.roleId);
    const roles = await RoleModel.find({ _id: { $in: roleIds } });

    const rolePermissions = await RolePermissionModel.find({
      roleId: { $in: roleIds },
    });
    const permissionIds = rolePermissions.map((rp) => rp.permissionId);
    const permissions = await PermissionModel.find({
      _id: { $in: permissionIds },
    });

    // 构建用户菜单权限（只包含二级菜单）
    const menuPermissions = permissions.filter((p) => p.parentId);

    // 生成双token，将用户信息、角色、权限编码到token中
    const userInfo = {
      id: user._id,
      userName: user.userName,
      realName: user.realName,
      email: user.email,
      phone: user.phone,
    };

    const tokens = generateTokens(userInfo, roles, menuPermissions);

    res.json({
      code: 200,
      message: "登录成功",
      data: {
        accessToken: tokens.accessToken,
        refreshToken: tokens.refreshToken,
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "登录失败",
      error: error.message,
    });
  }
});

// 发送重置密码验证码
router.post("/send-reset-code", async function (req, res, next) {
  try {
    const { email } = req.body;

    if (!email) {
      return res.status(400).json({
        code: 400,
        message: "邮箱地址不能为空",
      });
    }

    // 查找用户
    const user = await RbacUserModel.findOne({ email });
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: "该邮箱地址未注册",
      });
    }

    // 生成6位数验证码
    const verificationCode = Math.floor(
      100000 + Math.random() * 900000
    ).toString();

    // 设置验证码过期时间（10分钟）
    const expiresAt = new Date(Date.now() + 10 * 60 * 1000);

    // 存储验证码到数据库
    await RbacUserModel.findByIdAndUpdate(user._id, {
      resetCode: verificationCode,
      resetCodeExpires: expiresAt,
    });

    // 发送邮件
    const emailResult = await sendResetPasswordCode(
      email,
      verificationCode,
      user.realName
    );

    // 统一返回格式，验证码放在data中
    res.json({
      code: 200,
      message: "验证码发送成功",
      data: {
        email: email,
        verificationCode: verificationCode,
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "发送验证码失败",
      error: error.message,
    });
  }
});

// 重置密码
router.post("/reset-password", async function (req, res, next) {
  try {
    const { email, verificationCode, newPassword } = req.body;

    if (!email || !verificationCode || !newPassword) {
      return res.status(400).json({
        code: 400,
        message: "邮箱、验证码和新密码不能为空",
      });
    }

    // 查找用户
    const user = await RbacUserModel.findOne({ email });
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: "用户不存在",
      });
    }

    // 验证验证码
    if (!user.resetCode || user.resetCode !== verificationCode) {
      return res.status(400).json({
        code: 400,
        message: "验证码错误",
      });
    }

    // 检查验证码是否过期
    if (!user.resetCodeExpires || new Date() > user.resetCodeExpires) {
      return res.status(400).json({
        code: 400,
        message: "验证码已过期，请重新获取",
      });
    }

    // 检查新密码是否与旧密码相同
    if (newPassword === user.passWord) {
      return res.status(400).json({
        code: 400,
        message: "新密码与旧密码重复",
      });
    }

    // 更新密码并清除验证码
    await RbacUserModel.findByIdAndUpdate(user._id, {
      passWord: newPassword,
      resetCode: null,
      resetCodeExpires: null,
      updatedAt: new Date(),
    });

    res.json({
      code: 200,
      message: "密码重置成功",
      data: {
        email: email,
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "密码重置失败",
      error: error.message,
    });
  }
});

// 刷新访问令牌
router.post("/refresh-token", async function (req, res, next) {
  try {
    const { refreshToken } = req.body;

    if (!refreshToken) {
      return res.status(401).json({
        code: 401,
        message: "未提供刷新令牌",
      });
    }

    // 验证refresh token
    const decoded = verifyRefreshToken(refreshToken);

    // 查找用户确认用户仍然有效
    const user = await RbacUserModel.findById(decoded.userId);
    if (!user) {
      return res.status(401).json({
        code: 401,
        message: "用户不存在",
      });
    }

    if (user.status !== "active") {
      return res.status(403).json({
        code: 403,
        message: "用户已被禁用",
      });
    }

    // 获取用户角色和权限
    const userRoles = await UserRoleModel.find({ userId: user._id });
    const roleIds = userRoles.map((ur) => ur.roleId);
    const roles = await RoleModel.find({ _id: { $in: roleIds } });

    const rolePermissions = await RolePermissionModel.find({
      roleId: { $in: roleIds },
    });
    const permissionIds = rolePermissions.map((rp) => rp.permissionId);
    const permissions = await PermissionModel.find({
      _id: { $in: permissionIds },
    });

    // 构建用户菜单权限（只包含二级菜单）
    const menuPermissions = permissions.filter((p) => p.parentId);

    // 生成新的双token，将用户信息、角色、权限编码到token中
    const userInfo = {
      id: user._id,
      userName: user.userName,
      realName: user.realName,
      email: user.email,
      phone: user.phone,
    };

    const tokens = generateTokens(userInfo, roles, menuPermissions);

    res.json({
      code: 200,
      message: "刷新令牌成功",
      data: {
        accessToken: tokens.accessToken,
        refreshToken: tokens.refreshToken,
      },
    });
  } catch (error) {
    if (error.name === "TokenExpiredError") {
      return res.status(401).json({
        code: 401,
        message: "刷新令牌已过期，请重新登录",
      });
    }

    if (error.name === "JsonWebTokenError") {
      return res.status(401).json({
        code: 401,
        message: "刷新令牌无效",
      });
    }

    res.status(500).json({
      code: 500,
      message: "刷新令牌失败",
      error: error.message,
    });
  }
});








// ======我的======

// 获取用户列表
router.get("/yonghu", async function (req, res, next) {
  try {
    const { page = 1, limit = 10, search = "" } = req.query;
    const skip = (page - 1) * limit;

    let query = {};
    if (search) {
      query = {
        $or: [
          { username: { $regex: search, $options: "i" } },
          { nickname: { $regex: search, $options: "i" } },
          { email: { $regex: search, $options: "i" } },
          { phone: { $regex: search, $options: "i" } },
        ],
      };
    }

    const users = await YonghuUserModel.find(query)
      .skip(skip)
      .limit(parseInt(limit))
      .sort({ _id: 1 });

    const total = await YonghuUserModel.countDocuments(query);

    res.json({
      code: 200,
      message: "获取用户列表成功",
      data: {
        list: users,
        total,
        page: parseInt(page),
        limit: parseInt(limit),
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取用户列表失败",
      error: error.message,
    });
  }
});

// 获取单个用户
router.get("/yonghu/:id", async function (req, res, next) {
  try {
    const user = await YonghuUserModel.findOne({ id: req.params.id });
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: "用户不存在",
      });
    }

    // 从独立的订单表中获取用户的订单
    const orders = await YonghuOrderModel.find({ userId: req.params.id });

    // 从独立的优惠券表中获取用户的优惠券
    const coupons = await YonghuCouponModel.find({ userId: req.params.id });

    // 构建返回数据，包含用户信息、订单信息和优惠券信息
    const userData = {
      ...user.toObject(),
      orders: orders,
      coupons: coupons
    };

    res.json({
      code: 200,
      message: "获取用户信息成功",
      data: userData,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取用户信息失败",
      error: error.message,
    });
  }
});

// 获取用户优惠券列表
router.get("/yonghu/:id/coupons", async function (req, res, next) {
  try {
    const { 
      page = 1, 
      limit = 10, 
      status, 
      type, 
      category,
      search = "" 
    } = req.query;
    const skip = (page - 1) * limit;

    // 检查用户是否存在
    const user = await YonghuUserModel.findOne({ id: req.params.id });
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: "用户不存在",
      });
    }

    // 构建查询条件
    let query = { userId: req.params.id };
    
    // 状态筛选
    if (status) {
      query.status = status;
    }
    
    // 类型筛选
    if (type) {
      query.type = type;
    }
    
    // 分类筛选
    if (category) {
      query.category = category;
    }
    
    // 搜索功能
    if (search) {
      query.$or = [
        { name: { $regex: search, $options: 'i' } },
        { description: { $regex: search, $options: 'i' } },
        { couponId: { $regex: search, $options: 'i' } }
      ];
    }

    // 获取优惠券列表
    const coupons = await YonghuCouponModel.find(query)
      .skip(skip)
      .limit(parseInt(limit))
      .sort({ createdAt: -1 });

    // 获取总数
    const total = await YonghuCouponModel.countDocuments(query);

    res.json({
      code: 200,
      message: "获取优惠券成功",
      data: {
        list: coupons,
        total,
        page: parseInt(page),
        limit: parseInt(limit),
        totalPages: Math.ceil(total / parseInt(limit))
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取优惠券失败",
      error: error.message,
    });
  }
});

// 获取用户订单列表
router.get("/yonghu/:id/orders", async function (req, res, next) {
  try {
    const { 
      status, 
      page = 1, 
      limit = 10, 
      search = "",
      startDate,
      endDate,
      minAmount,
      maxAmount
    } = req.query;
    const skip = (page - 1) * limit;

    // 检查用户是否存在
    const user = await YonghuUserModel.findOne({ id: req.params.id });
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: "用户不存在",
      });
    }

    // 构建查询条件
    let query = { userId: req.params.id };
    
    // 状态筛选
    if (status) {
      query.status = status;
    }
    
    // 搜索功能 - 订单号、商品名称、收货地址
    if (search) {
      query.$or = [
        { orderId: { $regex: search, $options: 'i' } },
        { 'products.productName': { $regex: search, $options: 'i' } },
        { deliveryAddress: { $regex: search, $options: 'i' } },
        { caption: { $regex: search, $options: 'i' } }
      ];
    }
    
    // 日期范围筛选
    if (startDate || endDate) {
      query.orderTime = {};
      if (startDate) {
        query.orderTime.$gte = new Date(startDate);
      }
      if (endDate) {
        query.orderTime.$lte = new Date(endDate);
      }
    }
    
    // 金额范围筛选
    if (minAmount || maxAmount) {
      query.totalPrice = {};
      if (minAmount) {
        query.totalPrice.$gte = parseFloat(minAmount);
      }
      if (maxAmount) {
        query.totalPrice.$lte = parseFloat(maxAmount);
      }
    }

    // 获取订单列表
    const orders = await YonghuOrderModel.find(query)
      .skip(skip)
      .limit(parseInt(limit))
      .sort({ orderTime: -1 });

    // 获取总数
    const total = await YonghuOrderModel.countDocuments(query);

    res.json({
      code: 200,
      message: "获取订单列表成功",
      data: {
        list: orders,
        total,
        page: parseInt(page),
        limit: parseInt(limit),
        totalPages: Math.ceil(total / parseInt(limit))
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取订单列表失败",
      error: error.message,
    });
  }
});

// 新增用户
router.post("/yonghu", async function (req, res, next) {
  try {
    const {
      username,
      nickname,
      avatar,
      phone,
      email,
      password,
      vipLevel,
      gender,
      city,
    } = req.body;

    // 检查用户名是否已存在
    const existingUser = await YonghuUserModel.findOne({ username });
    if (existingUser) {
      return res.status(400).json({
        code: 400,
        message: "用户名已存在",
      });
    }

    // 生成用户ID
    const userId = `yonghu_${Date.now()}`;

    // 创建用户
    const user = new YonghuUserModel({
      _id: userId,
      username,
      nickname,
      avatar: avatar || "",
      phone,
      email,
      password,
      vipLevel: vipLevel || 0,
      points: 0,
      verified: false,
      gender: gender || "",
      city: city || "",
      wallet: {
        balance: 0,
        redPackets: 0,
        bonus: 0,
      },
      redPacketHistory: [],
    });

    const savedUser = await user.save();

    res.json({
      code: 200,
      message: "新增用户成功",
      data: savedUser,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "新增用户失败",
      error: error.message,
    });
  }
});

// 编辑用户
router.put("/yonghu/:id", async function (req, res, next) {
  try {
    const {
      username,
      nickname,
      avatar,
      phone,
      email,
      vipLevel,
      gender,
      city,
      status,
      verified,
      wallet,
    } = req.body;

    // 检查用户是否存在
    const user = await YonghuUserModel.findOne({ id: req.params.id });
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: "用户不存在",
      });
    }

    // 检查用户名是否被其他用户使用
    if (username && username !== user.username) {
      const existingUser = await YonghuUserModel.findOne({
        username,
        _id: { $ne: req.params.id },
      });
      if (existingUser) {
        return res.status(400).json({
          code: 400,
          message: "用户名已存在",
        });
      }
    }

    // 更新用户信息
    const updateData = {
      username: username || user.username,
      nickname: nickname || user.nickname,
      avatar: avatar !== undefined ? avatar : user.avatar,
      phone: phone || user.phone,
      email: email || user.email,
      vipLevel: vipLevel !== undefined ? vipLevel : user.vipLevel,
      gender: gender !== undefined ? gender : user.gender,
      city: city !== undefined ? city : user.city,
      status: status || user.status,
      verified: verified !== undefined ? verified : user.verified,
      lastLoginTime: new Date(),
      updatedAt: new Date(),
    };

    // 更新钱包信息
    if (wallet) {
      updateData.wallet = {
        balance:
          wallet.balance !== undefined ? wallet.balance : user.wallet.balance,
        redPackets:
          wallet.redPackets !== undefined
            ? wallet.redPackets
            : user.wallet.redPackets,
        bonus: wallet.bonus !== undefined ? wallet.bonus : user.wallet.bonus,
      };
    }

    const updatedUser = await YonghuUserModel.findOneAndUpdate(
      { id: req.params.id },
      updateData,
      { new: true }
    );

    res.json({
      code: 200,
      message: "编辑用户成功",
      data: updatedUser,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "编辑用户失败",
      error: error.message,
    });
  }
});

// 删除用户
router.delete("/yonghu/:id", async function (req, res, next) {
  try {
    const user = await YonghuUserModel.findOne({ id: req.params.id });
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: "用户不存在",
      });
    }

    // 删除用户
    await YonghuUserModel.findOneAndDelete({ id: req.params.id });

    res.json({
      code: 200,
      message: "删除用户成功",
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "删除用户失败",
      error: error.message,
    });
  }
});

// 添加优惠券
router.post("/yonghu/:id/coupons", async function (req, res, next) {
  try {
    const {
      couponId,
      name,
      type,
      discount,
      minAmount,
      category,
      startTime,
      endTime,
      description,
    } = req.body;

    // 检查用户是否存在
    const user = await YonghuUserModel.findOne({ id: req.params.id });
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: "用户不存在",
      });
    }

    // 生成优惠券ID
    const couponDbId = `coupon_${Date.now()}`;
    const couponIdGenerated = couponId || `CPN${Date.now()}`;

    const coupon = new YonghuCouponModel({
      id: couponDbId,
      userId: req.params.id,
      couponId: couponIdGenerated,
      name,
      type,
      discount,
      minAmount: minAmount || 0,
      category,
      status: "可使用",
      startTime: new Date(startTime),
      endTime: new Date(endTime),
      description: description || "",
    });

    await coupon.save();

    res.json({
      code: 200,
      message: "添加优惠券成功",
      data: coupon,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "添加优惠券失败",
      error: error.message,
    });
  }
});

// 删除优惠券
router.delete(
  "/yonghu/:userId/coupons/:couponId",
  async function (req, res, next) {
    try {
      const coupon = await YonghuCouponModel.findOneAndDelete({
        userId: req.params.userId,
        couponId: req.params.couponId
      });

      if (!coupon) {
        return res.status(404).json({
          code: 404,
          message: "优惠券不存在",
        });
      }

      res.json({
        code: 200,
        message: "删除优惠券成功",
      });
    } catch (error) {
      res.status(500).json({
        code: 500,
        message: "删除优惠券失败",
        error: error.message,
      });
    }
  }
);

// 修改优惠券状态
router.put(
  "/yonghu/:userId/coupons/:couponId/status",
  async function (req, res, next) {
    try {
      const { status } = req.body;

      // 验证状态值
      const validStatuses = ["可使用", "已使用", "已过期"];
      if (!validStatuses.includes(status)) {
        return res.status(400).json({
          code: 400,
          message: "无效的优惠券状态，支持的状态：" + validStatuses.join("、"),
        });
      }

      const coupon = await YonghuCouponModel.findOne({
        userId: req.params.userId,
        couponId: req.params.couponId
      });
      
      if (!coupon) {
        return res.status(404).json({
          code: 404,
          message: "优惠券不存在",
        });
      }

      // 更新优惠券状态
      coupon.status = status;
      coupon.updatedAt = new Date();

      await coupon.save();

      res.json({
        code: 200,
        message: "优惠券状态修改成功",
        data: {
          couponId: coupon.id,
          name: coupon.name,
          status: coupon.status,
          type: coupon.type,
          discount: coupon.discount,
        },
      });
    } catch (error) {
      res.status(500).json({
        code: 500,
        message: "修改优惠券状态失败",
        error: error.message,
      });
    }
  }
);

// 添加订单
router.post("/yonghu/:id/orders", async function (req, res, next) {
  try {
    const {
      orderId,
      products,
      paymentMethod,
      deliveryAddress,
      caption,
    } = req.body;

    const user = await YonghuUserModel.findOne({ id: req.params.id });
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: "用户不存在",
      });
    }

    // 计算订单总数量和总价格
    const totalQuantity = products.reduce((sum, product) => sum + product.quantity, 0);
    const totalPrice = products.reduce((sum, product) => sum + product.subtotal, 0);

    // 生成订单ID
    const orderIdGenerated = orderId || `ORD${Date.now()}`;
    const orderDbId = `order_${Date.now()}`;

    const order = new YonghuOrderModel({
      id: orderDbId,
      userId: req.params.id,
      orderId: orderIdGenerated,
      products: products.map(product => ({
        productId: product.productId,
        productName: product.productName,
        price: product.price,
        quantity: product.quantity,
        subtotal: product.subtotal
      })),
      totalQuantity,
      totalPrice,
      status: "待付款",
      orderTime: new Date(),
      paymentMethod: paymentMethod || "",
      deliveryAddress,
      pickupCode: "",
      completedTime: null,
      refundReason: "",
      refundAmount: 0,
      refundTime: null,
      caption: caption || "",
    });

    await order.save();

    res.json({
      code: 200,
      message: "添加订单成功",
      data: order,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "添加订单失败",
      error: error.message,
    });
  }
});

// 更新订单状态
router.put("/yonghu/:userId/orders/:orderId", async function (req, res, next) {
  try {
    const {
      status,
      paymentMethod,
      pickupCode,
      completedTime,
      refundReason,
      refundAmount,
      refundTime,
    } = req.body;

    const order = await YonghuOrderModel.findOne({ 
      userId: req.params.userId,
      orderId: req.params.orderId 
    });
    
    if (!order) {
      return res.status(404).json({
        code: 404,
        message: "订单不存在",
      });
    }

    // 更新订单信息
    if (status) order.status = status;
    if (paymentMethod) order.paymentMethod = paymentMethod;
    if (pickupCode) order.pickupCode = pickupCode;
    if (completedTime) order.completedTime = new Date(completedTime);
    if (refundReason) order.refundReason = refundReason;
    if (refundAmount !== undefined) order.refundAmount = refundAmount;
    if (refundTime) order.refundTime = new Date(refundTime);
    order.updatedAt = new Date();

    await order.save();

    res.json({
      code: 200,
      message: "更新订单成功",
      data: order,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "更新订单失败",
      error: error.message,
    });
  }
});

// 添加红包历史
router.post("/yonghu/:id/redpackets", async function (req, res, next) {
  try {
    const { amount, date } = req.body;

    const user = await YonghuUserModel.findOne({ id: req.params.id });
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: "用户不存在",
      });
    }

    const redPacket = {
      id: `RP${Date.now()}`,
      date: date ? new Date(date) : new Date(),
      amount,
      status: "可使用",
    };

    user.redPacketHistory.push(redPacket);

    // 更新用户钱包中的红包金额
    user.wallet.redPackets += amount;

    await user.save();

    res.json({
      code: 200,
      message: "添加红包记录成功",
      data: redPacket,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "添加红包记录失败",
      error: error.message,
    });
  }
});

// 获取用户统计信息
router.get("/yonghu/:id/statistics", async function (req, res, next) {
  try {
    const user = await YonghuUserModel.findOne({ id: req.params.id });
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: "用户不存在",
      });
    }

    // 从独立的订单表中获取订单数据
    const orders = await YonghuOrderModel.find({ userId: req.params.id });

    // 从独立的优惠券表中获取优惠券数据
    const coupons = await YonghuCouponModel.find({ userId: req.params.id });

    const statistics = {
      totalOrders: orders.length,
      totalAmount: orders.reduce(
        (sum, order) => sum + order.totalPrice,
        0
      ),
      totalCoupons: coupons.length,
      availableCoupons: coupons.filter((c) => c.status === "可使用")
        .length,
      usedCoupons: coupons.filter((c) => c.status === "已使用").length,
      expiredCoupons: coupons.filter((c) => c.status === "已过期").length,
      totalRedPackets: user.redPacketHistory ? user.redPacketHistory.length : 0,
      totalRedPacketAmount: user.redPacketHistory ? user.redPacketHistory.reduce(
        (sum, rp) => sum + rp.amount,
        0
      ) : 0,
      orderStatus: {
        待付款: orders.filter((o) => o.status === "待付款").length,
        待发货: orders.filter((o) => o.status === "待发货").length,
        待提货: orders.filter((o) => o.status === "待提货").length,
        待评价: orders.filter((o) => o.status === "待评价").length,
        退款中: orders.filter((o) => o.status === "退款中").length,
        已退款: orders.filter((o) => o.status === "已退款").length,
      },
    };

    res.json({
      code: 200,
      message: "获取用户统计信息成功",
      data: statistics,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取用户统计信息失败",
      error: error.message,
    });
  }
});

// 上传头像
router.post(
  "/yonghu/upload-avatar",
  upload.single("avatar"),
  async function (req, res, next) {
    try {
      if (!req.file) {
        return res.status(400).json({
          code: 400,
          message: "请选择要上传的图片",
        });
      }

      // 返回头像URL
      const avatarUrl = `/upload/avatars/${req.file.filename}`;

      res.json({
        code: 200,
        message: "头像上传成功",
        data: {
          avatarUrl: avatarUrl,
        },
      });
    } catch (error) {
      console.error("上传头像失败:", error);
      res.status(500).json({
        code: 500,
        message: "上传头像失败",
        error: error.message,
      });
    }
  }
);

// 上传凭证照片
router.post('/yonghu/upload-evidence', evidenceUpload.single('evidence'), async function(req, res, next) {
  try {
    if (!req.file) {
      return res.status(400).json({
        code: 400,
        message: '请选择要上传的图片'
      });
    }

    // 返回照片URL和其他信息
    const evidenceUrl = `/upload/evidence/${req.file.filename}`;
    
    res.json({
      code: 200,
      message: '凭证照片上传成功',
      data: {
        key: `evidence_${Date.now()}_${Math.random()}`,
        url: evidenceUrl,
        filename: req.file.filename,
        originalname: req.file.originalname,
        size: req.file.size,
        mimetype: req.file.mimetype
      }
    });
  } catch (error) {
    console.error('上传凭证照片失败:', error);
    res.status(500).json({
      code: 500,
      message: '上传凭证照片失败',
      error: error.message
    });
  }
});

// 创建支付宝支付订单
router.post('/yonghu/create-payment', async function(req, res, next) {
  try {
    const { orderId, amount, productNames, userId } = req.body;
    
    if (!orderId || !amount || !userId) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数'
      });
    }

    // 生成商户订单号
    const outTradeNo = `ORDER_${userId}_${orderId}_${Date.now()}`;
    
    // 构建支付参数
    const bizContent = {
      outTradeNo: outTradeNo, //商户订单号
      productCode: 'FAST_INSTANT_TRADE_PAY', //产品码
      totalAmount: amount.toFixed(2), //总金额
      subject: productNames ? productNames.join(', ') : `订单${orderId}`, //订单标题
      body: `订单${orderId}的支付`,
      timeoutExpress: '30m', // 30分钟超时
    };

    // 使用AlipayFormData创建支付表单
    const formData = new AlipayFormData();
    formData.setMethod('get');
    formData.addField('bizContent', bizContent);
    formData.addField('returnUrl', 'http://localhost:5173/my/payment-success'); // 支付成功后的跳转URL
    formData.addField('notifyUrl', 'https://77361d7ffe18.ngrok-free.app/hy/yonghu/payment-callback'); // 支付宝回调URL
    
    // 生成支付URL
    const result = await alipaySdk.exec(
      'alipay.trade.page.pay',
      {}, // api 请求的参数（包含"公共请求参数"和"业务参数"）
      { formData: formData },
    );

    res.json({
      code: 200,
      message: '支付订单创建成功',
      data: {
        payUrl: result,
        outTradeNo: outTradeNo,
        orderId: orderId
      }
    });
  } catch (error) {
    console.error('创建支付订单失败:', error);
    res.status(500).json({
      code: 500,
      message: '创建支付订单失败',
      error: error.message
    });
  }
});

// 支付宝支付回调
router.post('/yonghu/payment-callback', async function(req, res, next) {
  try {
    const params = req.body;
    
    console.log('=== 支付宝回调开始 ===');
    console.log('回调参数:', params);
    
    // 验证支付宝回调签名
    const signVerified = alipaySdk.checkNotifySign(params);
    console.log('签名验证结果:', signVerified);
    
    if (!signVerified) {
      console.error('支付宝回调签名验证失败');
      return res.status(400).send('fail');
    }

    // 处理支付结果
    const { out_trade_no, trade_status, trade_no } = params;
    
    console.log('支付状态:', trade_status);
    console.log('商户订单号:', out_trade_no);
    console.log('支付宝交易号:', trade_no);
    
    if (trade_status === 'TRADE_SUCCESS') {
      console.log('支付成功，开始处理订单更新...');
      
      // 从outTradeNo中提取userId和orderId
      // outTradeNo格式: ORDER_${userId}_${orderId}_${timestamp}
      const orderMatch = out_trade_no.match(/^ORDER_(.+)_(.+)_\d+$/);
      if (!orderMatch) {
        console.error('无法从outTradeNo中提取userId和orderId:', out_trade_no);
        return res.status(400).send('fail');
      }
      console.log('orderMatch',orderMatch);
      const userId = orderMatch[1];
      const orderId = orderMatch[2];
      
      // 查找订单
      const order = await YonghuOrderModel.findOne({ 
        userId: userId,
        orderId: orderId 
      });
      
      if (!order) {
        console.error('未找到订单:', orderId, '用户ID:', userId);
        return res.status(404).send('fail');
      }
      
      // 更新订单状态
      order.status = '待发货';
      
      // 更新或创建支付相关字段
      order.paymentMethod = '支付宝';
      order.tradeNo = trade_no;
      order.paidTime = new Date();
      order.outTradeNo = out_trade_no;
      order.updatedAt = new Date();
      
      // 保存更新
      await order.save();
      
      console.log('支付成功:', out_trade_no, '用户ID:', userId, '订单ID:', orderId);
    }

    res.send('success');
  } catch (error) {
    console.error('支付回调处理失败:', error);
    res.status(500).send('fail');
  }
});

// 查询支付状态
router.get('/yonghu/payment-status/:outTradeNo', async function(req, res, next) {
  try {
    const { outTradeNo } = req.params;
    
    // 从outTradeNo中提取userId和orderId
    const orderMatch = outTradeNo.match(/^ORDER_(.+)_(.+)_\d+$/);
    if (!orderMatch) {
      return res.status(400).json({
        code: 400,
        message: '无效的outTradeNo格式'
      });
    }
    
    const userId = orderMatch[1];
    const orderId = orderMatch[2];
    
    // 查找订单
    const order = await YonghuOrderModel.findOne({ 
      userId: userId,
      orderId: orderId 
    });
    
    if (!order) {
      return res.status(404).json({
        code: 404,
        message: '订单不存在'
      });
    }
    
    res.json({
      code: 200,
      message: '查询成功',
      data: {
        orderId: order.orderId,
        status: order.status,
        paymentMethod: order.paymentMethod,
        paidTime: order.paidTime,
        outTradeNo: order.outTradeNo
      }
    });
  } catch (error) {
    console.error('查询支付状态失败:', error);
    res.status(500).json({
      code: 500,
      message: '查询支付状态失败',
      error: error.message
    });
  }
});

// 前端主动查询并更新支付状态
router.post('/yonghu/check-payment-status', async function(req, res, next) {
  try {
    const { userId, orderId, outTradeNo } = req.body;
    
    if (!userId || !orderId || !outTradeNo) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数'
      });
    }
    
    console.log('前端主动查询支付状态:', { userId, orderId, outTradeNo });
    
    // 先查找用户
    // 查找订单
    const order = await YonghuOrderModel.findOne({ 
      userId: userId,
      orderId: orderId 
    });
    
    if (!order) {
      console.error('未找到订单:', orderId, '用户ID:', userId);
      return res.status(404).json({
        code: 404,
        message: '订单不存在'
      });
    }
    
    console.log('当前订单状态:', order.status);
    
    // 如果订单状态还是"待付款"，则更新为"待发货"
    if (order.status === '待付款') {
      order.status = '待发货';
      order.paymentMethod = '支付宝';
      order.tradeNo = 'FRONTEND_' + Date.now();
      order.paidTime = new Date();
      order.outTradeNo = outTradeNo;
      order.updatedAt = new Date();
      
      await order.save();
      
      console.log('前端主动更新支付状态成功:', outTradeNo, '用户ID:', userId, '订单ID:', orderId);
      console.log('更新后的订单状态:', order.status);
    } else {
      console.log('订单状态已经是:', order.status, '，无需更新');
    }
    
    res.json({
      code: 200,
      message: '支付状态查询成功',
      data: {
        orderId: order.orderId,
        status: order.status,
        paymentMethod: order.paymentMethod,
        paidTime: order.paidTime,
        outTradeNo: order.outTradeNo
      }
    });
  } catch (error) {
    console.error('查询支付状态失败:', error);
    res.status(500).json({
      code: 500,
      message: '查询支付状态失败',
      error: error.message
    });
  }
});

// 修改用户个人信息
router.put("/yonghu/:id/profile", async function (req, res, next) {
  try {
    const { nickname, avatar, gender, phone, email } = req.body;

    const user = await YonghuUserModel.findOne({ id: req.params.id });
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: "用户不存在",
      });
    }

    // 更新个人信息
    const updateData = {
      nickname: nickname || user.nickname,
      avatar: avatar !== undefined ? avatar : user.avatar,
      gender: gender !== undefined ? gender : user.gender,
      phone: phone || user.phone,
      email: email || user.email,
      updatedAt: new Date(),
    };

    const updatedUser = await YonghuUserModel.findOneAndUpdate(
      { id: req.params.id },
      updateData,
      { new: true } //返回更新后的用户
    );

    res.json({
      code: 200,
      message: "修改个人信息成功",
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "修改个人信息失败",
      error: error.message,
    });
  }
});

// 修改订单状态
router.put(
  "/yonghu/:userId/orders/:orderId/status",
  async function (req, res, next) {
    try {
      const { status } = req.body;

      // 验证状态值
      const validStatuses = [
        "待付款",
        "待发货",
        "待提货",
        "待评价",
        "退款中",
        "已退款",
      ];
      if (!validStatuses.includes(status)) {
        return res.status(400).json({
          code: 400,
          message: "无效的订单状态，支持的状态：" + validStatuses.join("、"),
        });
      }

      const order = await YonghuOrderModel.findOne({ 
        userId: req.params.userId,
        orderId: req.params.orderId 
      });
      
      if (!order) {
        return res.status(404).json({
          code: 404,
          message: "订单不存在",
        });
      }

      // 更新订单状态
      order.status = status;

      // 根据状态更新相关时间
      if (status === "待评价") {
        order.completedTime = new Date();
      }
      
      order.updatedAt = new Date();

      await order.save();

      res.json({
        code: 200,
        message: "订单状态修改成功",
        data: {
          orderId: order.orderId,
          status: order.status,
          completedTime: order.completedTime,
        },
      });
    } catch (error) {
      res.status(500).json({
        code: 500,
        message: "修改订单状态失败",
        error: error.message,
      });
    }
  }
);

// 修改红包状态
router.put(
  "/yonghu/:userId/redpackets/:redPacketId/status",
  async function (req, res, next) {
    try {
      const { status } = req.body;

      // 验证状态值
      const validStatuses = ["可使用", "已使用", "已过期"];
      if (!validStatuses.includes(status)) {
        return res.status(400).json({
          code: 400,
          message: "无效的红包状态，状态必须为：可使用、已使用、已过期",
        });
      }

      const user = await YonghuUserModel.findOne({ id: req.params.userId });
      if (!user) {
        return res.status(404).json({
          code: 404,
          message: "用户不存在",
        });
      }

      // 验证红包是否存在
      const redPacket = await YonghuCouponModel.findOne({
        userId: req.params.userId,
        couponId: req.params.redPacketId
      });
      
      if (!redPacket) {
        return res.status(404).json({
          code: 404,
          message: "红包不存在",
        });
      }

      // 更新红包状态
      redPacket.status = status;
      redPacket.updatedAt = new Date();

      await redPacket.save();

      res.json({
        code: 200,
        message: "红包状态修改成功",
      });
    } catch (error) {
      res.status(500).json({
        code: 500,
        message: "修改红包状态失败",
        error: error.message,
      });
    }
  }
);

// 手动检查优惠券过期状态（调试用）
router.post("/check-coupon-expiry", async function (req, res, next) {
  try {
    const { userId } = req.body;
    const socketServer = require("../socket/socketServer");

    if (userId) {
      // 检查指定用户的优惠券
      await socketServer.checkUserCouponExpiry(userId, null);
      res.json({
        code: 200,
        message: `用户 ${userId} 的优惠券过期检查已执行`,
      });
    } else {
      // 检查所有用户的优惠券
      await socketServer.checkAndUpdateExpiredCoupons();
      res.json({
        code: 200,
        message: "所有用户的优惠券过期检查已执行",
      });
    }
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "检查优惠券过期失败",
      error: error.message,
    });
  }
});

// 秒杀活动列表
router.get("/flash-sale/activities", (req, res) => {
  res.json({
    code: 200,
    data: {
      list: [
        {
          id: 1,
          name: "春季秒杀活动",
          time: "2021-03-02 ~ 2021-03-12",
          productCount: 10,
          status: "进行中",
          online: "上线",
        },
        {
          id: 2,
          name: "夏季秒杀活动",
          time: "2021-06-01 ~ 2021-06-10",
          productCount: 8,
          status: "未开始",
          online: "下线",
        },
        {
          id: 3,
          name: "双11大促",
          time: "2021-11-01 ~ 2021-11-11",
          productCount: 20,
          status: "已结束",
          online: "上线",
        },
      ],
      total: 3,
    },
  });
});
// 新建活动
router.post("/flash-sale/activities", (req, res) => {
  res.json({ code: 200, message: "新建成功" });
});
// 编辑活动
router.put("/flash-sale/activities/:id", (req, res) => {
  res.json({ code: 200, message: "编辑成功" });
});
// 删除活动
router.delete("/flash-sale/activities/:id", (req, res) => {
  res.json({ code: 200, message: "删除成功" });
});
// 下线活动
router.post("/flash-sale/activities/:id/offline", (req, res) => {
  res.json({ code: 200, message: "下线成功" });
});

module.exports = router;
